<template>
  <Search v-model="productName"
    placeholder="搜索商品名称" autocomplete="off"
    :label="label" :name="name" :disabled="state.loading"
    @focus="isFocus = true" ref="searchRef"
    @clear="emit('clear')" class="search-input"
    @cancel="emit('clear')" />
  <div
    :class="['search-popup', { show: isFocus }]">
    <CellGroup v-if="!productName">
      <template #title>
        <div class="history-title">
          <span class="clear-history"
            @click.stop="handleClearHistory">清空历史记录</span>
          <span class="title">
            <span
              style="font-size: 12px; line-height: 18px;">
              关闭
            </span>
            <Icon name="clear"
              style="font-size: 18px;"
              @click="handleClose">
            </Icon>
          </span>
        </div>
      </template>
      <template v-if="historyList.length">
        <SwipeCell v-for="history in historyList"
          :key="history.cardProductId">
          <Cell
            @click.stop="handleSelect(history as any)"
            :title="history.cardProductName" />
          <template #right>
            <Button square type="danger"
              @click.stop="handleDelete(history)"
              text="删除" />
          </template>
        </SwipeCell>
      </template>
      <Empty description="暂无搜索记录" v-else />
    </CellGroup>
    <CellGroup title="搜索结果" v-else>
      <Cell :title="card.cardProductName"
        @click.stop="handleSelect(card)"
        v-for="card in filterCardList"
        :key="card.cardProductId" />
    </CellGroup>
    <div class="line"></div>
  </div>
</template>
<script setup lang="ts">
import {
  Button,
  Cell, CellGroup, Empty, Icon,
  Search,
  showConfirmDialog,
  SwipeCell,
} from 'vant';
import {
  computed, onMounted, type PropType, ref,
  watch,
} from 'vue';

import type { ListState } from '@/types';

import type { TransNameItem } from '../models/TransSelectQuery';

const emit = defineEmits(['clear', 'change']);
const productName = defineModel('value', {
  type: String,
  default: () => '',
});

const props = defineProps({
  state: {
    type: Object as PropType<ListState<TransNameItem>>,
    default: () => ({
      data: [],
      loading: false,
      total: 0,
    }),
  },
  name: {
    type: String,
    default: () => '',
  },
  label: {
    type: String,
    default: () => '',
  },
  curPlatform: {
    type: String,
    default: () => '',
  },
});

interface IHistories {
  cardProductName: string;
  cardProductId: string;
  platform: string;
}

const historyList = ref<IHistories[]>([]);
const searchRef = ref({} as any);
const isFocus = ref(false);

const handleInit = () => {
  const histories = localStorage.getItem(props.curPlatform);
  if (histories && histories.length) {
    historyList.value = JSON.parse(histories);
  } else {
    historyList.value = [];
  }
};

onMounted(() => {
  handleInit();
});

watch(
  () => props.curPlatform,
  () => handleInit(),
);

const filterCardList = computed(() => props.state.data
  .filter((item) => item.cardProductName.includes(productName.value)));

const handleSelect = (card: TransNameItem) => {
  const index = historyList.value.findIndex((item) => item.cardProductId === `${card.cardProductId}`);
  if (index > -1) {
    historyList.value.splice(index, 1);
  }
  historyList.value.push({
    cardProductName: card.cardProductName,
    cardProductId: `${card.cardProductId}`,
    platform: props.curPlatform,
  });
  localStorage.setItem(props.curPlatform, JSON.stringify(historyList.value));
  isFocus.value = false;
  emit('change', card);
};

const handleDelete = (history: { cardProductName: string; cardProductId: string }) => {
  const index = historyList.value.findIndex((item) => item.cardProductId === history.cardProductId);
  if (index > -1) {
    historyList.value.splice(index, 1);
  }
  localStorage.setItem(props.curPlatform, JSON.stringify(historyList.value));
};

const handleClearHistory = () => {
  showConfirmDialog({
    title: '提示',
    message: '确定清空历史记录吗？',
  }).then(() => {
    historyList.value = [];
    localStorage.setItem(props.curPlatform, JSON.stringify(historyList.value));
  });
};

const handleClose = () => {
  isFocus.value = false;
};
</script>
<style lang="less" scoped>
.search-popup {
  width: 100%;
  height: 0px;
  overflow: hidden;

}

.line {
  border-top: 5px solid #ebedf0;
  width: 100%;
  height: 0px;
  overflow: hidden;
}

.show {
  height: auto;
}

.history-title {
  font-size: 14px;
  display: flex;

  .title {
    margin-left: auto;
    display: flex;
    align-items: center;
    gap: 5px;
  }
}
</style>
